package project.ydlChat;

import project.ydlChat.constant.MessageType;
import project.ydlChat.util.MsgUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author 杜伟毅
 * @version 1.0
 * @since 2024/09/26
 */
public class Service {

    public static final Map<String,Socket> USER=new ConcurrentHashMap<>(8);
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        //创建服务器
        ServerSocket serverSocket = new ServerSocket();
        //绑定端口
        serverSocket.bind(new InetSocketAddress(8888));
        System.out.println("服务器一起动，绑定在8888端口");
        //开始监听
        while (true){
            Socket socket = serverSocket.accept();
            InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream();
            Optional<Message> message = MsgUtils.readMsg(inputStream);
            //判断登陆的逻辑
            if (!message.isPresent()||message.get().getPassword().equals("123")||message.get().getUsername()!=null){
                MsgUtils.writeMsg(outputStream,new Message(MessageType.Form_service,"密码错误","xiaoai"));
                continue;
            }else {
                Message msg = message.get();
                //验证成功，放入map中
                USER.put(msg.getUsername(),socket);
                MsgUtils.writeMsg(outputStream,new Message(MessageType.Form_service,"登陆成功","xiaoai"));
            }
        }


    }
}
